package com.guoxin.concurrentcy.chapter13;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("all")
public class SimpleThreadPool {

    private final int size;
    private final int queueSize;
    private final DiscardPolicy discardPolicy;
    private volatile int seq = 0;

    private static final int DEFAULT_SIZE = 10;
    private static final LinkedList<Runnable> TASK_QUEUE = new LinkedList<>();
    private static final ThreadGroup DEFAULT_THREAD_GROUP = new ThreadGroup("SIMPLE_THREAD_GROUP");
    private static final String THREAD_POOL_PRIFIX = "SIMPLE_THREAD-";
    private static final List<WorkerTask> THREAD_QUEUE = new ArrayList<>();
    private static final int DEFAULT_TASK_QUEUE_SIZE = 2000;

    private static final DiscardPolicy DEFAULT_DISCARD_POLICY = () -> {
        throw new DiscardException("被拒绝.....");
    };

    private volatile boolean distory;

    public SimpleThreadPool(int size, int queueSize, DiscardPolicy discardPolicy) {
        this.size = size;
        this.queueSize = queueSize;
        this.discardPolicy = discardPolicy;
        init();
    }

    public SimpleThreadPool() {
        this(DEFAULT_SIZE, DEFAULT_TASK_QUEUE_SIZE, DEFAULT_DISCARD_POLICY);
    }

    public void submit(Runnable runnable) {
        if (distory) {
            throw new IllegalStateException("非法状态");
        }
        synchronized (TASK_QUEUE) {
            if (TASK_QUEUE.size() > queueSize) {
                discardPolicy.discard();
            }
            TASK_QUEUE.addLast(runnable);
            TASK_QUEUE.notifyAll();
        }
    }

    public void shutdown() throws InterruptedException {
        while (!TASK_QUEUE.isEmpty()) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        int initVal = THREAD_QUEUE.size();
        while (initVal > 0) {
            for (WorkerTask task : THREAD_QUEUE) {
                if (task.taskStatus == TaskStatus.BLOCKED) {
                    task.interrupt();
                    task.close();
                    initVal--;
                } else {
                    Thread.sleep(50);
                }
            }
        }
        this.distory = true;
        System.out.println("The Thread pool disposed.");

    }

    public static class DiscardException extends RuntimeException {
        public DiscardException(String message) {
            super(message);
        }
    }

    public interface DiscardPolicy {

        void discard() throws DiscardException;
    }

    public int getSize() {
        return size;
    }

    public int getQueueSize() {
        return queueSize;
    }

    public boolean getDistory() {
        return this.distory;
    }


    private void init() {
        for (int i = 0; i < size; i++) {
            createWorkerTask();
        }
    }

    private void createWorkerTask() {
        WorkerTask task = new WorkerTask(DEFAULT_THREAD_GROUP, THREAD_POOL_PRIFIX + (seq++));
        task.start();
        THREAD_QUEUE.add(task);
    }

    private enum TaskStatus {
        //
        FREE, RUNNING, BLOCKED, DEAD;
    }

    private static class WorkerTask extends Thread {
        private volatile TaskStatus taskStatus = TaskStatus.FREE;

        WorkerTask(ThreadGroup threadGroup, String name) {
            super(threadGroup, name);
        }

        @Override
        public void run() {
            OUTER:
            while (this.taskStatus != TaskStatus.DEAD) {
                Runnable runnable;
                synchronized (TASK_QUEUE) {
                    while (TASK_QUEUE.isEmpty()) {
                        try {
                            taskStatus = TaskStatus.BLOCKED;
                            TASK_QUEUE.wait();
                        } catch (InterruptedException e) {
                            break OUTER;
                        }
                    }
                    runnable = TASK_QUEUE.removeFirst();
                }

                if (runnable != null) {
                    taskStatus = TaskStatus.RUNNING;
                    runnable.run();
                    taskStatus = TaskStatus.FREE;
                }
            }
        }

        public void close() {
            taskStatus = TaskStatus.DEAD;
        }

    }

    public static void main(String[] args) throws InterruptedException {
        SimpleThreadPool pool = new SimpleThreadPool();
        for (int i = 0; i < 100; i++) {
            final int index = i;
            pool.submit(() -> {
                        try {
                            System.out.println("The runnable " + index + " is serviced by " + Thread.currentThread().getName() + " running");
                            Thread.sleep(100);
                            System.out.println("The runnable " + index + " is serviced by " + Thread.currentThread().getName() + " done");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
            );
        }
        Thread.sleep(3000);
        pool.shutdown();
    }

}
